#include "dtwentyitem.h"


#include <QTimer>


DTwentyItem::DTwentyItem(QObject *parent) :
    ModelItem(parent),
    d(new Data())
{
}

DTwentyItem::DTwentyItem(const DTwentyItem &other) :
    ModelItem(other),
    d(other.d)
{
}

int DTwentyItem::type() const
{
    return qMetaTypeId<DTwentyItem*>();
}

QString DTwentyItem::typeName() const
{
    QString ret = QMetaType::typeName(type());
    ret = ret.remove("*");
    return ret;
}


bool DTwentyItem::removable() const
{
    return true;
}


QString DTwentyItem::referencePath() const
{
    return d->referencePath;
}

void DTwentyItem::setReferencePath(const QString &referencePath)
{
    if (d->referencePath == referencePath)
    {
        return;
    }

    d->referencePath = referencePath;

    QTimer::singleShot(0, this, SLOT(onResolveReference()));
}

void DTwentyItem::setReferenceItem(DTwentyItem *referenceItem)
{
    if (!d->referenceItem.isNull())
    {
        disconnect(d->referenceItem, SIGNAL(nameChanged));
    }

    d->referenceItem = referenceItem;

    if (!referenceItem)
    {
        return;
    }

    onRefreshReference();

    connect(d->referenceItem.data(), &ModelItem::nameChanged, this, &DTwentyItem::onRefreshReference);
    connect(d->referenceItem.data(), &QObject::destroyed, this, &QObject::deleteLater);
}

void DTwentyItem::onResolveReference()
{
    DTwentyItem* referenceItem = rootItem()->findChild<DTwentyItem*>(d->referencePath);

    setReferenceItem(referenceItem);
}

void DTwentyItem::onRefreshReference()
{
    if (d->referenceItem.isNull())
    {
        d->referencePath.clear();
        setName("[none]");
        return;
    }

    d->referencePath = d->referenceItem->objectName();
    setName(d->referenceItem->name());
}

const DTwentyItem *DTwentyItem::parentItem() const
{
    return qobject_cast<const DTwentyItem*>(parent());
}



